package chapter3;

import org.omg.CORBA.TIMEOUT;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * @author : Neo
 * @version : V1.0
 * @date :2017/11/18 12:07
 * @description :
 */
public class NioClientDemo {

	private Selector selector;
	public void initClient(String ip,int port)throws Exception {
		SocketChannel channel = SocketChannel.open();
		channel.configureBlocking(false);
		this.selector = Selector.open();
		channel.connect(new InetSocketAddress(ip,port));
		channel.register(selector, SelectionKey.OP_CONNECT);
	}
	public void listen()throws Exception {

		while (true) {
			selector.select();
			Iterator ite = this.selector.selectedKeys()
										 .iterator();
			while (ite.hasNext()) {
				SelectionKey key = (SelectionKey) ite.next();
				ite.remove();
				if (key.isConnectable()) {
					SocketChannel channel = (SocketChannel) key.channel();
					if (channel.isConnectionPending()) {
						channel.finishConnect();
					}
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap("hello from cliteen".getBytes()));
					channel.register(this.selector, SelectionKey.OP_READ);
				}
				else if (key.isReadable()) {
					read(key);
				}

			}


		}
	}

	Integer i=0;
	private void read(SelectionKey key)  throws Exception{
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(100);
		channel.read(buffer);
		byte[] data = buffer.array();
		String msg=new String(data).trim();
		msg+=i.toString();
		System.out.println("服务端收到信息:"+msg);
		TimeUnit.SECONDS.sleep(1);


		ByteBuffer outbuffer = ByteBuffer.wrap(msg.getBytes());
		channel.write(outbuffer);

	}

	public static void main(String[] args) throws Exception {
		NioClientDemo clientDemo = new NioClientDemo();
		int port=8080;
		clientDemo.initClient("127.0.0.1",port);
		clientDemo.listen();
	}


}
